import { getUserInfo, setUserPhone, login } from '../../services/user'
import { getUserCenterTag } from '../../services/order'
import { ORDER_STATE_NAME_ARR } from '../../services/const'

const app = getApp()

Page({
  data: {
    canIUseAuthButton: true,
    userInfo: {},
    location: {},
    entries: [
      {
        isactive: false,
        orderStatus: 10,
        title: '待支付',
        cover: '../../asserts/n1.png',
      },
      {
        isactive: false,
        orderStatus: 0,
        title: ORDER_STATE_NAME_ARR[0],
        cover: '../../asserts/n6.png',
      },
      {
        isactive: false,
        orderStatus: 1,
        title: ORDER_STATE_NAME_ARR[1],
        cover: '../../asserts/n2.png',
      },
      {
        isactive: false,
        orderStatus: 2,
        title: ORDER_STATE_NAME_ARR[2],
        cover: '../../asserts/n3.png',
      },
      {
        isactive: false,
        orderStatus: 4,
        title: ORDER_STATE_NAME_ARR[4],
        cover: '../../asserts/n4.png',
      },
      ...app.globalData.playforminfo.mode === 'rental' ? 
      [{
        isactive: false,
        orderStatus: 5,
        title: ORDER_STATE_NAME_ARR[5],//用户侧提交回寄就变更为待结算
        cover: '../../asserts/n5.png',
      },
      {
        isactive: false,
        orderStatus: 7,
        title: ORDER_STATE_NAME_ARR[7],
        cover: '../../asserts/n7.png',
      }] : []
    ],
    servers: [
      {
        title: '优惠券',
        cover: '../../asserts/p1.png',
        url: '/pages/my-ticket/my-ticket'
      },
      {
        title: '产品建议',
        cover: '../../asserts/p2.png',
        url: '/pages/consult/consult'
      },

      {
        title: '领券中心',
        cover: '../../asserts/p3.png',
        url: '/pages/get-ticket/get-ticket'

      },
      {
        title: '我的地址',
        cover: '../../asserts/p4.png',
        url: '/pages/shipping/shipping'
      }
    ],
    navList: [
      {
        name: '我的订单',
        thumb: 'https://gw.alipayobjects.com/mdn/rms_107da2/afts/img/A*Y8BATYqMN78AAAAAAAAAAABkARQnAQ',
        onClick: () =>
          my.navigateTo({
            url: '/pages/my-order/my-order?id=0&orderStatus=0',
          }),
      },
      {
        name: '我的券',
        thumb: 'https://gw.alipayobjects.com/mdn/rms_107da2/afts/img/A*9RqXQaxLeCEAAAAAAAAAAABkARQnAQ',
        onClick: () =>
          my.navigateTo({
            url: '/pages/my-ticket/my-ticket',
          }),
      },
      {
        name: '关于',
        thumb: 'https://gw.alipayobjects.com/mdn/rms_107da2/afts/img/A*-Lp1TZDggnoAAAAAAAAAAABkARQnAQ',
        onClick: () => { },
      },
    ],
  },
  async onLoad() {
    my.setNavigationBar({
      title: '我的',
      backgroundColor: '#0384FF'
    })

    const userInfo = await app.silenceLogin()

    if (userInfo) {
      this.setData({ userInfo })
      this.getUserCenterTag()
    }
  },
  toKf() {
    my.switchTab({
      url: '/pages/customer/customer',
    })
  },
  toOrder(event) {
    my.navigateTo({
      url: '/pages/my-order/my-order?orderStatus=' + event.target.dataset.orderStatus
    })
  },
  onListClick({ target: { dataset } }) {
    const { onClick } = this.data.navList[dataset.index];
    if (onClick) {
      onClick();
    }
  },
  updateUserPhone(encryptedData) {
    setUserPhone({ encryptedData }).then(({code, data}) => {
      if (code == 0) {
        const { userInfo } = this.data
        userInfo.phone = data.phone
        app.globalData.userInfo = userInfo
        
        this.setData({ userInfo })
      }
    })
  },
  async onGetAuthorize() {
    let encryptedData = ''

    my.getPhoneNumber({
      success: (res) => {
        encryptedData = JSON.parse(res.response).response
      }
    })

    const res = await my.getAuthCode({
      scopes: 'auth_base',
    })
    
    if (!res || (res.authErrorScopes && Object.keys(res.authErrorScopes).length)) {
      return my.showToast({
        type: 'fail',
        content: '登录异常',
        duration: 2000,
      })
    }

    my.getOpenUserInfo({
      success: async (ret) => {
        let userInfo = JSON.parse(ret.response).response
        console.log('userInfo', userInfo)
        const { code, data } = await login({ code: res.authCode, userInfo })
        if (code === 0) {
          app.globalData.userInfo = data
          this.setData({ userInfo: data })
          !data.phone && this.updateUserPhone(encryptedData)
        }
      },
      fail: (ret) => {
        my.showToast({
          type: 'fail',
          content: '登录授权异常',
          duration: 2000,
        });
      },
    });
  },
  getLocation() {
    var that = this;
    my.showLoading();
    my.getLocation({
      type: 1,
      success(res) {
        my.hideLoading();
        console.log(res)
        that.setData({
          location: res
        })
      },
      fail() {
        my.hideLoading();
        my.alert({ title: '定位失败' });
      },
    })
  },
  entriesTap(event) {
    console.log(event)
    if (event.target.dataset.url) {
      my.navigateTo({
        url: event.target.dataset.url
      })
    }
  },
  contract() {
    let flowId = 'b0a94bc8288b41bbbbaaec67e63b41ea'
    let thirdPartyUserId = '920f4c357e004a8d9b161dac561dd453'
    let skipResult = true
    let skipGuide = false
    let url = `plugin://esign/esign?flowId=${flowId}&signerId=${thirdPartyUserId}&skipResult=${skipResult}&skipGuide=${skipGuide}`
    console.log(url)
    my.navigateTo({
      url: url
    })
  },
  async getUserCenterTag() {
    const { code, data } = await getUserCenterTag()

    if (code != 0 || !data.length) return false

    const { entries } = this.data
    
    entries.forEach(item => {
      item.isactive = data[item.orderStatus] ? true : false
    })
    
    this.setData({ entries })
  }
});

